package middleware

import (
	"bytes"
	"exercise/application/yiran/app/libs"
	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
	"io/ioutil"
	"time"
)

func LoggerMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {

		start := time.Now()
		path := ctx.Request.URL.Path
		query := ctx.Request.URL.RawQuery
		post := ""

		if ctx.Request.Method == "POST" {
			// 把request的内容读取出来
			bodyBytes, _ := ioutil.ReadAll(ctx.Request.Body)
			ctx.Request.Body.Close()
			// 把刚刚读出来的再写进去
			ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
			switch ctx.ContentType() {
			case "application/json":
				var result map[string]interface{}
				d := jsoniter.NewDecoder(bytes.NewReader(bodyBytes))
				d.UseNumber()
				if err := d.Decode(&result); err == nil {
					bt, _ := jsoniter.Marshal(result)
					post = string(bt)
				}
			default:
				post = string(bodyBytes)
			}
		}
		ctx.Next()
		cost := time.Since(start)
		libs.LoggerSysInfo(map[string]interface{}{
			"status":     ctx.Writer.Status(),
			"method":     ctx.Request.Method,
			"path":       path,
			"query":      query,
			"post":       post,
			"ip":         ctx.ClientIP(),
			"user-agent": ctx.Request.UserAgent(),
			"errors":     ctx.Errors.ByType(gin.ErrorTypePrivate).String(),
			"cost":       cost,
		})
	}
}
